StartPage.Gmail=(function(){return{
	label: null, httpRequest: null, timerTimeout: null, interval: null 
	,init: function(){
		this.httpRequest = Cc["@mozilla.org/xmlextras/xmlhttprequest;1"].createInstance(Ci.nsIXMLHttpRequest);
		this.timerTimeout = Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer);
		var self=this
		if (!this.interval) this.interval=setInterval(function(){ self.check.call(self) }, 30000);
		this.updateLabel();
	}
	,updateLabel: function(txt){
		if (txt || txt===0) this.label=txt;
		if (typeof this.label=='undefined' || this.label==null){ this.check(); return; }
		var label=$('#startpage-apps a.gmail span.counter', gBrowser.contentDocument);
		label.removeClass('error loading');
		if (this.label=='loading'){ label.addClass('loading'); label.attr('title','Checking...'); }
		else if(this.label=='error'){ label.addClass('error'); label.attr('title','Server error. Try loging in'); }
		else { label.attr('title','You have '+this.label+' unread items'); label.text(this.label); }
	}
	,check: function(){
		var self=this
		this.updateLabel('loading');
		this.httpRequest.open('GET', 'https://mail.google.com/mail/feed/atom', true);
		this.httpRequest.onload = function(){ self.reqSuccess.call(self); }
		this.httpRequest.onerror = function(){ self.reqError.call(self); }
		this.httpRequest.send(null);
		var event = { notify: function(timer){ self.reqError.call(self) } }
		this.timerTimeout.initWithCallback(event,10000, Ci.nsITimer.TYPE_ONE_SHOT);
	}
	,reqSuccess: function(){
		this.timerTimeout.cancel();
		var unreadCount, output = $(this.httpRequest.responseXML);
		if (output.length){ 
			if (output.find('fullcount')) unreadCount=output.find('fullcount').text();
			else unreadCount='error';
		}		
		else unreadCount='error';
		this.httpRequest.abort(); // reset variable to decrease usage memory
			//var sound = Cc["@mozilla.org/sound;1"].createInstance(Ci.nsISound), IO = Cc["@mozilla.org/network/io-service;1"].getService(Ci.nsIIOService); sound.play(IO.newURI('chrome://startpage/content/mail.wav', null, null));
		if (unreadCount=='error') this.updateLabel('error'); 
		else this.updateLabel(unreadCount);
	}
	,reqError: function(){ this.timerTimeout.cancel(); this.updateLabel('error');	}	
}}());
